<?php

//会员签到
class MembersSignModel extends BaseModel {

    public function tableName() {
        return '{{members_sign}}'; //数据库表名称
    }

    //建立规则
    public function rules() {
        return array(
            array('uid', 'required', 'message' => 'UID用户名不能为空！'), //前两行有规定，required表示不能为空
            array('signtime,signtype,ip,number', 'safe'), //validate验证
        );
    }

    //静态模型，可直接调用模型
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    //数据保存前置操作
    protected function beforeSave() {
        //是否新增
        if ($this->isNewRecord) {
            $this->signtime = time();
            $this->ip = GuestDataModel::model()->getForwardedForIp();
        }
        return true;
    }

    /**
     * 判断今天是否已经签到过了
     * @param type $uid 用户UID
     * @return boolean FALSE 没有签到过，TRUE 已经签到
     */
    public function isSignIn($uid, $signtype = 0) {
        if (empty($uid)) {
            return FALSE;
        }
        //增加缓存
        $key = "userSing_{$uid}_{$signtype}";
        $cache = Yii::app()->cache->get($key);
        if (!empty($cache)) {
            return true;
        }
        $time = strtotime(date('Y-m-d')); // 获取时间戳
        switch ((int) $signtype) {
            case 0:
                $count = $this->count($this->where(array('signtime' => array('GT', $time), 'uid' => $uid, 'signtype' => $signtype)));
                break;
            case 1:
                $count = $this->count($this->where(array('signtime' => array('GT', $time), 'uid' => $uid, 'signtype' => $signtype)));
                break;
            default:
                $this->addError('', '平台错误,请求非法!');
                break;
        }
        if ($count == 0) {
            return FALSE;
        } else {
            $cacheTime = strtotime(date('Y-m-d 23:58:50')) - time();
            Yii::app()->cache->set($key, 1, $cacheTime);
            return TRUE;
        }
    }

    /**
     * 根据UID获取当前月份的已经签到的天数 数组
     * @param type $uid
     * return array("日"=>"1");
     */
    public function getMonthArrayByUid($uid) {
        if (empty($uid)) {
            return array();
        }
        $time = time();
        $maxdays = date('t', $time);
        $min_start_time = strtotime(date('Y-m-1 00:00:00', $time));
        $max_start_time = strtotime(date('Y-m-' . $maxdays . ' 23:59:59', $time));
        $data = $this->findAll($this->where(array(
                    'signtime' => array(array('LT', $max_start_time), array('GT', $min_start_time), 'AND'),
                    'uid' => $uid)));
        if ($data) {
            foreach ($data as $d) {
                $return[(int) date('d', $d->signtime)] = 1;
            }
        }
        return $return;
    }

    /**
     *  签到日历本,显示已经签到的天
     * @param type $uid
     */
    public function getCalendarHtml($uid) {
        $y = $this->getMonthArrayByUid($uid);
        if ($uid) {
            $model = MembersModel::model()->findByPk((int) $uid);
            $score = $model->score;
        } else {
            $score = 0;
        }
        $mdays = date("t");    //当月总天数  
        $datedatenow = date("j");  //当日日期  
        $monthnow = date("n"); //当月月份  
        $yearnow = date("Y");  //当年年份  
        //计算当月第一天是星期几  
        $wk1st = date("w", mktime(0, 0, 0, $monthnow, 1, $yearnow));
        $trnum = ceil(($mdays + $wk1st) / 7); //计算表格行数  
        //以下是表格字串   height:246px;
        $tabstr = '
     <style type="text/css">  
    .qiandaodiv {position:absolute;z-index:99;width:305px;border-style:solid;border-color:#dfdfdf;background:#fff;padding:10px;font-family:arial;right:0;}
    #tc_calendar{width:303px;}
    #tc_calendar{border-collapse:collapse;}

    #tc_calendar td{text-align:center;height:25px;line-height:25px;border-bottom:1px solid #fff;border-right:1px solid #fff;}
    #tc_calendar .even td{background-color:#fff;}
    #tc_calendar .even .gray{background-color:#f5f5f5;}
    #tc_calendar td .current{display:block;background-color:#f60;color:#fff;}
    #tc_calendar .current{background-color:#ffa19c!important;color:#fff;}
    #tc_week td{color:black;background-color:#FFFFFF;height:15px;border-bottom:1px solid #f5f5f5;}
    #top_yyyy_mm {color:#FFFFFF;background-color:#FF6600; text-align:center; height:30px;line-height:30px;}
    #tc_jifen  {background-color:#ffff;height:30px;}
    .jifen_left{float:left;height:30px;line-height:30px;}
    .jifen_right{float:right;height:30px;line-height:30px;}
    </style> ';

        $tabstr .= " <div id='qiandaodiv' class='qiandaodiv' style='display:block;'><div id=tc_jifen ><div class='jifen_left'>签到 <font color='#f1453d'>+5分</font></div> <div class='jifen_right'>我的积分<font color='#f1453d'> $score</font></div></div>"
                . "<div  id='top_yyyy_mm'> $yearnow 年 $monthnow 月</div>"
                . "<table id=tc_calendar><tr id=tc_week><td>周日</td><td>周一</td><td>周二</td><td>周三</td><td>周四</td><td>周五</td><td>周六</td></tr>";
        for ($i = 0; $i < $trnum; $i++) {
            $tabstr.="<tr class=even>";
            for ($k = 0; $k < 7; $k++) { //每行七个单元格  
                $tabidx = $i * 7 + $k; //取得单元格自身序号  
                $todaybg = '';
                $background = '';
                //若单元格序号小于当月第一天的星期数($wk1st)或大于(月总数+$wk1st)  
                //只填写空格，反之，写入日期  
                ($tabidx < $wk1st or $tabidx > $mdays + $wk1st - 1) ? $dayecho = "&nbsp" : $dayecho = $tabidx - $wk1st + 1;
                //突出标明今日日期  
                //$dayecho="<span style=\"background-color:red;color:#fff;\">$dayecho</span>";  
                //$dayecho=array(); 
                if (isset($y[$dayecho]) && $y[$dayecho]) {
                    $todaybg = " current ";
                }
                if ($k == 0 || $k == 6) {
                    $background = " gray ";
                }
                $tabstr.="<td class='" . $background . " " . $todaybg . "'>$dayecho</td>";
            }
            $tabstr.="</tr>";
        }
        $tabstr.="</table></div>";
        echo $tabstr;
    }

    /**
     * 签到
     * @param type $uid
     * @return boolean FALSE 签到不成功，返回的赠送的积分数
     */
    public function signIn($uid, $signtype = 0) {
        if (empty($uid)) {
            $this->addError(' uid ', 'uid不能为空!');
            return false;
        }
        //是否手机第一次签到
        $isPo = $this->isFirstSign($uid);
        if ($this->isSignIn($uid, $signtype) === FALSE) {
            $this->signtype = $signtype;
            $this->uid = $uid;
            //设置此次保存的时候number值            
            $this->setLast($uid, $signtype);            
            if ($this->validate() && $this->save()) {   // 需要验证条件 validate
                // 日常送积分
                $score = 5;
                if ($this->signtype == 0) {
                    MembersModel::model()->plusScore($uid, $score, '登录签到，系统赠送积分' . $score . '。');
                    //经验值
                    MembersModel::model()->plusExp($uid, 1, '登录签到，经验值加1。');
                } else if ($this->signtype == 1) {
                    if ($isPo) {
                        $score = 50;
                        //经验值
                        MembersModel::model()->plusExp($uid, 5, '首次手机登录签到，经验值加5。');
                    } else {
                        $score = 10;
                        //经验值
                        MembersModel::model()->plusExp($uid, 2, '手机登录签到，经验值加2。');
                    }
                    MembersModel::model()->plusScore($uid, $score, '手机登录签到，系统赠送积分' . $score . '。');
                }
                // 当累计达到10天或20天时额外赠送积分
                $this->signRules();
                return $score;
            } else {
                return false;
            }
        } else {
            $this->addError('', '今天您已经签到过了！');
            return false;
        }
    }
    /**
     * 获取此用户最后一条签到数据，且看是否是昨天的
     * @param  [type] $uid      [description]
     * @param  [type] $signtype [description]
     * @return [type]           [description]
     */
    public function setLast($uid, $signtype){
        $last_model = self::model()->find(array('condition' => 'uid = :uid AND signtype = :signtype', 'params' => array('uid' => $uid, 'signtype' => $signtype), 'order' => 'signid desc'));                       
        if($last_model){
            //如果最后一条是昨天的
            if($last_model->signtime >= strtotime('yesterday') && $last_model->signtime < strtotime('today')){
                if($last_model->number >= 20){
                    $this->number = 1;
                }else{
                    $this->number = $last_model->number + 1;
                }                
            }else{
                $this->number = 1;//这次签到是第一条
            }
        }else{
            $this->number = 1;//这次签到是第一条
        }
    }


    /**
     * 获取积分规则，设置连续签到积分
     * @param type $uid
     * @param type $signtype 设备类型
     * @return boolean 
     */
    public function signRules() {
        switch($this->number){
            case 10:
                if($this->signtype == 0){
                    $note = '网站连续签到10次，系统赠送积分50.';                    
                }else{
                    $note = '手机连续签到10次，系统赠送积分50.';  
                }
                MembersModel::model()->plusScore($this->uid, 50, $note);
            break;

            case 20:
                if($this->signtype == 0){
                    $note = '网站连续签到20次，系统赠送积分150.';                    
                }else{
                    $note = '手机连续签到20次，系统赠送积分150.';  
                }
                MembersModel::model()->plusScore($this->uid, 150, $note);
            break;
        }    
    }

    /**
     * 间隔时间10天或20天的签到次数
     * @param type $uid
     * @param type $day
     * @return type
     */
    public function getThisSignTime($uid, $signtype, $day = 9) {
        $timeday = (int) date('d') - $day;
        $firsttime = strtotime(date('Y-m-' . $timeday));
        $objThis = $this->where(array('uid' => $uid, 'signtime' => array('EGT', $firsttime), 'signtype' => $signtype));
        $count = $this->count($objThis);
        if ($count) {
            return $count;
        }
        return 0;
    }

    /**
     * 判断用户是否是首次签到
     * @return boolean [description]
     */
    public function isFirstSign($uid, $signtype = 1) {
        $criteria = new CDbCriteria(array('condition' => 'uid = :uid', 'params' => array('uid' => $uid)));
        $criteria->compare('signtype', $signtype);
        $obj = $this->count($criteria);
        if ($obj == 0) {
            return true;
        }
        return false;
    }

//根据uid去查询他的签到记录
//    public function checkSignRecord($uid) {
//        $offset = (int) $_GET['offset'];
//        $limit = 20;
//        $criteria = $this->where(array('uid' => $this->uid));
//        $count= $this->count($criteria);
//        $criteria->limit = $limit;
//        $criteria->offset = $offset;
//        $signr = $this->findAll($criteria);
//        $data=array();
//        foreach ($signr as $p ) {
//            $data[] =$p->attributes;
//        }
//        return $data;
//    }    
}
